/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */
var dependsList = [
    'element', 'layer', 'form', 'table', '$http',
    'laydate', 'zmnTable', 'NP', 'select2', 'zmnUtils', 'zmnSelect', 'zmnOmsSelect'
];
layui.define(dependsList, function(exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laydate = layui.laydate;
    var zmnTable = layui.zmnTable;
    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var NP = layui.NP;

    let zmnOmsSelect = layui.zmnOmsSelect;
    let zmnSelect = layui.zmnSelect;

    let json = {
        vo: {
            orgLimitPermit: dpermitOrgIdList && dpermitOrgIdList.length > 0 ? true : false, // 没有配置组织架构，不引用权限
            companyId: null,
        }
    };

    // 会员远程查询 URL
    var MASTER_LIST_URL = '/staff/master/list.action';
    var PART_LIST_URL = '/partsku/list.action';
    var PART_CATEG_LIST_URL = '/partsku/categ/list.action';
    var CITY_LIST_URL = '/area/company/city/list.action';

    // 时间选择器字段容器
    var datePickerSelectorArray = [
        'accountTime', // 算账时间
        'partReimburseTime', // 配件报销时间
    ];

    // 多选择字段容器
    var multipleSelectNameArray = [];

    /**
     * 模板工具
     * @type {{formatMasterInfo, formatUserInfo, formatReplayState}}
     */
    var templateUtils = (function() {
        function maskPhone(phone) {
            return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '';
        }

        return {
            formatMoneyToYuan: function(field) {
                return function(data) {
                    var money = data[field];
                    if (!money) {
                        money = '0.00';
                    } else {
                        money = NP.round(NP.divide(money, 100), 2);
                        money = money.toFixed(2);
                    }

                    return money;
                }
            }
        }
    })();

    // 表格配置
    var tableConfig = {
        defaultParams: {},
        initialSearch: false,
        orderObj: {},
        exportURL: '/order_part/exportexcel',
        config: {
            url: '/order_part/ajax/list.action',
            cols: [
                [
                    { field: 'orderId', title: '工单' },
                    { field: 'masterName', title: '工程师' },
                    { field: 'cityName', title: '城市' },
                    { field: 'partTypeName', title: '配件类型', align: 'center' },
                    { field: 'partName', title: '配件' },
                    { field: 'number', title: '使用数量', align: 'center' },
                    { field: 'unit', title: '单位', align: 'center' },
                    { field: 'amount', title: '金额', templet: templateUtils.formatMoneyToYuan('amount') },
                    { field: 'reimburseStatusName', title: '报销状态' },
                    { field: 'reimburseTime', title: '报销时间', sort: true },
                    { field: 'accountTime', title: '算账时间', sort: true }
                ]
            ]
        }
    };

    /**
     * 转换数量（新业务模式不需要转换，暂时注释）
     * @param obj
     */
    /*function conversionNumber(obj) {
        let conver = conversionMap[obj.partId];
        if (conver) {
            return NP.round(NP.divide(obj.number, conver.scale), 2);
        } else {
            return obj.number || "";
        }
    }*/

    /**
     * 转换单位（新业务模式不需要转换，暂时注释）
     * @param obj
     */
    /*function conversionUnit(obj) {
        let conver = conversionMap[obj.partId];
        if (conver) {
            return conver.unit;
        } else {
            return obj.unit || "";
        }
    }*/

    /**
     * 渲染日期选择器
     * @param selector 日期选择器的选择器或者 Dom 对象
     */
    function renderDatePicker(selector) {
        var config = {
            elem: selector,
            format: selector.indexOf('Start') !== -1 ? 'yyyy-MM-dd' : 'yyyy-MM-dd'
        };

        var $selector = $(selector);
        if ($selector) {
            var minTime = $selector.data('min') || defaultMinTime;
            if (minTime) {
                config.min = minTime;
            }
        }
        laydate.render(config);
    }

    /**
     * 初始化页面的所有日期组件
     */
    function initALLDatePickers() {
        $.each(datePickerSelectorArray, function(index, keyword) {
            $.each(['Start', 'End'], function(i, suffix) {
                renderDatePicker('#' + keyword + suffix);
            });
        });
    }

    /**
     * 渲染表格
     * @param {object} params 查询参数
     * @returns {object}
     */
    function renderTable(params, data) {
        return zmnTable.init({
            config: {
                ...tableConfig.config,
                elem: '#zmn-part-table',
                id: 'zmn-part-table',
                method: 'POST',
                contentType: 'application/json;charset=utf-8',
                limit: 100,
                limits: [100],
                data: data,
                where: {
                    ...tableConfig.orderObj,
                    ...params
                },
                parseData: function(res) {
                    return {
                        "code": res.status, //解析接口状态
                        "msg": res.message, //解析提示文本
                        "count": res.data ? (res.data.count > 10000 ? 10000 : res.data.count) : 0, //解析数据长度
                        "data": res.data ? res.data.data : [] //解析数据列表
                    };
                },
                done: function(res, curr, count) {
                    $('.layui-this').find('.count').text('（共 ' + count + ' 条）');
                }
            },
            filter: 'zmn-part-table',

            event: function() {
                table.on('tool(zmn-work-table)', function(rowObj) {
                    if (rowObj.event === 'operate') {}
                });

                table.on('rowDouble(zmn-work-table)', function(rowObj) {

                });

                // 监听头工具栏事件
                table.on('toolbar(zmn-work-table)', function(obj) {

                });
            }
        });
    }

    var getters = {
        getCompanyId: () => $('#companyId').val()
    };

    /**
     * 搜索框搜索方法
     * @param {object} params 查询参数
     */
    function searchForTable(params, data) {
        tableInstance = renderTable(params, data);
    }


    /**
     * 标准化搜索参数
     * @param {object} field 参数
     */
    function normalizeSearchParams(field) {
        var params = {};

        // 整理时间
        datePickerSelectorArray.forEach(function(keyword) {
            var startSelector = keyword + '.start';
            var endSelector = keyword + '.end';

            if ($('#' + keyword + 'Start').closest('.date-picker-item').hasClass('inline-block')) {
                var startTime = field[startSelector];
                var endTime = field[endSelector];

                if (startTime || endTime) {
                    startTime = startTime ? startTime + ' ' + '00:00:00' : '';
                    endTime = endTime ? endTime + ' ' + '23:59:59' : '';

                    params[keyword] = startTime + ',' + endTime;
                }
            }

            field[startSelector] = '';
            field[endSelector] = '';
        });

        // 整理工单号
        if (field['code'] && field['code'].length) {
            if (field['code'].length > 19) {
                field['code'] = field['code'].substring(0, 19);
            }

            if (field['code'].length === 6) {
                params['codeEnd6'] = field['code'];
                field['code'] = '';
            }
        }

        // 整理操作类型、操作员
        if (field['operate.operateType'] || field['operate.operatorId']) {
            params['operate'] = {
                operateType: field['operate.operateType'],
                operatorId: field['operate.operatorId']
            };

            field['operate.operateType'] = null;
            field['operate.operatorId'] = null;
        }

        // 整理加单工程师
        if (field['addMaster.operatorId']) {
            params['addMaster'] = {
                operatorId: field['addMaster.operatorId']
            };

            field['addMaster.operatorId'] = null;
        }

        // 拷贝非空字段
        Object.keys(field).filter((key) => {
            if (field[key]) {
                if (multipleSelectNameArray.indexOf(key) !== -1) {
                    params[key] = field[key].split(',');
                } else {
                    params[key] = field[key];
                }
            }
        });

        return params;
    }

    /**
     * 初始化城市下拉框
     */
    var initPartCategtSelect = (function() {
        /**
         * 根据配件一级分类获取二级分类
         * @param params 查询参数
         * @returns {*}
         * @private
         */
        function _fetchPartCategByCategOne(params) {
            return $http.$get(PART_CATEG_LIST_URL, params);
        }

        /**
         * 渲染配件小类下拉框
         * @param {object} data 区域数据
         * @private
         */
        function _renderPartCategSelect(data) {
            var htmlStr = '<option value="">全部</option>';
            data.forEach(function(item) {
                htmlStr += '<option value="' + item.value + '">' + item.text + '</option>';
            });

            $('#select-part-categ').html(htmlStr);
            form.render();
        }

        return function(categOneId) {
            if (!categOneId) {
                _renderPartCategSelect([]);
            }

            _fetchPartCategByCategOne({ categOneId: categOneId }).then((data) => {
                _renderPartCategSelect(data);
            }, () => {
                _renderPartCategSelect([]);
            });
        }
    })();

    /**
     * 初始化城市下拉框
     */
    var initCityListSelect = (function() {
        /**
         * 根据公司id 获取城市数据
         * @param params 查询参数
         * @returns {*}
         * @private
         */
        function _fetchCityListByCompanyId(params) {
            return $http.$get(CITY_LIST_URL, params);
        }

        /**
         * 渲染城市下拉框
         * @param data 城市数据
         * @private
         */
        function _renderCityListSelect(data) {
            var htmlStr = '<option value="">全部</option>';
            data.forEach(function(item) {
                htmlStr += '<option value="' + item.value + '">' + item.text + '</option>';
            });

            $('#select-city').html(htmlStr);
            form.render();
        }

        return function(companyId) {
            if (!companyId) {
                _renderCityListSelect([]);
            }

            _fetchCityListByCompanyId({ companyId: companyId }).then((data) => {
                _renderCityListSelect(data);
            }, () => {
                _renderCityListSelect([]);
            });
        }
    })();


    /**
     * 格式化工程师列表列表项
     * @param {object} repo
     * @returns {string}
     */
    function formatRepoForMaster(repo) {
        if (repo.loading) {
            return '查询中...'
        }
        var name = repo.text + (repo.disabled ? '（离职）' : '');
        var markup = '<div><div><i class="zmn-icon zmn-icon-worker"></i><span>' + name + '</span></div><div><i class="zmn-icon zmn-icon-phone"></i><span>' + repo.ext1 + '</span></div></div>';

        return markup;
    }

    /**
     * 使用 Select2 初始化工程师下拉框
     */
    function initMasterSelecteBySelect2() {
        $('#select-master').select2({
            theme: "layui",
            language: 'zh-CN',
            placeholder: '全部',
            allowClear: true,
            minimumInputLength: 1,
            dropdownAutoWidth: true,
            ajax: {
                url: MASTER_LIST_URL,
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    var query = {
                        plat: plat,
                        text: params.term,
                        companyId: getters.getCompanyId()
                    }

                    return query;
                },
                processResults: function(response) {
                    var results = [];
                    if (response.status === 200) {
                        results = response.data;
                    }
                    results = results.map((item) => {
                        item.id = item.value;
                        return item;
                    });

                    return {
                        results: results
                    };
                }
            },
            escapeMarkup: function(markup) { return markup; },
            templateResult: formatRepoForMaster,
            // dropdownCssClass: 'aaa'
        });
    }

    /**
     * 格式化工程师列表列表项
     * @param {object} repo
     * @returns {string}
     */
    function formatRepoForPart(repo) {
        if (repo.loading) {
            return '查询中...'
        }

        return repo.text;
    }

    /**
     * 使用 Select2 初始化配件下拉框
     */
    function initPartSelecteBySelect2() {
        $('#select-part').select2({
            theme: "layui",
            language: 'zh-CN',
            placeholder: '全部',
            allowClear: true,
            minimumInputLength: 1,
            dropdownAutoWidth: true,
            ajax: {
                url: PART_LIST_URL,
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    var query = {
                        text: params.term
                    }

                    return query;
                },
                processResults: function(response) {
                    var results = [];
                    if (response.status === 200) {
                        results = response.data;
                    }
                    results = results.map((item) => {
                        item.id = item.value;
                        return item;
                    });

                    return {
                        results: results
                    };
                }
            },
            escapeMarkup: function(markup) { return markup; },
            templateResult: formatRepoForPart,
            // dropdownCssClass: 'aaa'
        });
    }

    /**
     * 初始化页面所有需要使用 Select2 的下拉框
     */
    function initAllRemoteSelectBySelect2() {
        // zmnSelect.selectSubCompany('companyId', {
        //     isRadio: true,
        //     isReload: true
        // });

        zmnSelect.selectSubCompany('companyId', {
            isRadio: true,
            isReload: true,
            page: {
                enable: true,
                pageSize: 50
            },
            remote: {
                limitPermit: json.vo.orgLimitPermit,
                events: {
                    extendParams: function() {
                        return { plat: plat }
                    }
                }
            },
            events: {
                changed: function(values) {
                    console.log("==========companyId=========");
                    console.log("已选中的值:" + values);
                    json.vo.companyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                }
            }
        });

        zmnSelect.selectCity('cityIdList', {
            tips: "-选择城市-",
            isRadio: true,
            isReload: true,
        });

        zmnSelect.searchEngineer('masterId', {
            isRadio: true,
            remote: {
                limitPermit: json.vo.orgLimitPermit,
                events: {
                    extendParams: function() {
                        return {
                            plat: plat,
                            companyId: json.vo.companyId
                        }
                    }
                }
            },
            events: {
                changed: function(values) {
                    console.log("========engineerIds=========")
                    console.log("已选中的值:" + values)
                }
            }
        });

        initPartSelecteBySelect2();
    }

    /**
     * 初始化查询条件
     */
    function initQueryParams() {
        if (!defaultQuery) {
            return;
        }

        tableConfig.defaultParams = {};

        $('.tab-work-list .layui-tab-title li').removeClass('layui-this');

        // 用户id
        if (defaultQuery.userId) {
            tableConfig.defaultParams['userId'] = defaultQuery.userId;
            tableConfig.initialSearch = true;
        }

        // 会员id
        if (defaultQuery.memberId) {
            tableConfig.defaultParams['memberId'] = defaultQuery.memberId;
            tableConfig.initialSearch = true;
        }

        // 工单号
        if (defaultQuery.id) {
            tableConfig.defaultParams['code'] = defaultQuery.id;
            tableConfig.initialSearch = true;
        }
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('body').on('input', 'input', function() {
            var $this = $(this);
            $this.val($this.val().replace(/(^\s*)|(\s*$)/g, ''));
        });

        // 监听重置按钮点击
        $('button[type="reset"]').on('click', function() {
            setTimeout(function() {
                $('input').val('');
                $('select').val('');
                form.render('select');
            }, 100);
        });

        // 监听分公司下拉框选择事件
        form.on('select(select-company)', function(data) {
            var value = data.value;

            initCityListSelect(value);
        });

        // 监听时间选择器控制选择框点击事件
        form.on('checkbox(datepicker)', function(data) {
            var $dataPicker = $('.date-picker-item').eq(data.value);
            if (data.elem.checked) {
                $dataPicker.addClass('inline-block').find('input').attr('disabled', false);
            } else {
                $dataPicker.removeClass('inline-block').find('input').attr('disabled', false);;
            }

            form.render();
        });

        // 监听配件大类下拉框选择事件
        form.on('select(partCategOne)', function(data) {
            var value = data.value;

            initPartCategtSelect(value);
        });

        // 监听查询表单提交事件
        form.on('submit(submit-search)', function(obj) {
            var params = normalizeSearchParams(obj.field);
            let pageUrl = window.location.href;
            var filter_name = ''
            Object.keys(params).forEach((item, index) => {
                var fifname = $('[name^="' + item + '"]').parents('.layui-input-inline').eq($('[name^="' + item + '"]').parents('.layui-input-inline').length - 1).prev().text().split('：')[0]

                if (index != Object.keys(params).length - 1) {
                    filter_name = filter_name + fifname + '|'
                } else {
                    filter_name = filter_name + fifname
                }

            })

            try {
                if (filter_name.substring(filter_name.length - 1) == '|') {
                    filter_name = filter_name.substring(0, filter_name.length - 1)
                }
                console.log(filter_name)
                var data = {
                    employee_name: loginStaff.realName, // 内部员工姓名,
                    employee_id: loginStaff.staffId,
                    department_name: loginStaff.deptName, // 员工部门名称
                    department_id: loginStaff.deptId,
                    menu: path_name, //菜单目录路径名称
                    filter_name: filter_name,
                    tab_name: tabName || ''
                }
                webTrackingUtil('SYS_ADMIN_QUERY', pageUrl, 'click', 'SYS_ADMIN_QUERY_CLICK', data)
            } catch (error) {
                console.log(error)
            }

            if (!Object.keys(params).length) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            searchForTable(params);
            return false;
        });

        // 监听查询表单导出事件
        form.on('submit(submit-export)', function(obj) {
            var params = normalizeSearchParams(obj.field);

            if (!Object.keys(params).length) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            if (!tableConfig.exportURL) {
                layer.msg('请添加导出 URL');
                return false;
            }

            layui.zmnUtils.exportFile(tableConfig.exportURL, params);
            return false;
        });
    }

    /**
     * 初始化页面
     */
    function initPage() {
        initAllRemoteSelectBySelect2();

        // 初始化页面所有的日期选择器
        initALLDatePickers();
        // 初始化查询条件
        initQueryParams();

        // 渲染 table
        if (tableConfig.initialSearch) {
            searchForTable(tableConfig.defaultParams);
        } else {
            searchForTable({}, []);
        }

        // 初始化页面数据
        initEvent();
    }

    initPage();
    exports('oms_part_list');
});